//
//  MainViewController.m
//  XMCalculator
//
//  Created by dc on 2017/6/13.
//  Copyright © 2017年 DMY. All rights reserved.
//

//数字键盘宽
#define kBasicWidth  kDeviceWidth / 4.0
//数字键盘高
#define kbasicHeight  kBasicWidth / 1.3
//屏幕输入文字font大小
#define kCalcuLabFontSize 40.0
//屏幕输入框高度
#define kCalcuLabHeight 50.0
//屏幕输入框宽度
#define kCalcuLabWidth 25.0


#import "MainViewController.h"

@interface MainViewController ()
@property(nonatomic,strong)NSMutableArray *calcuArr;
@property(nonatomic,strong)UIScrollView *calcuBoxView;
@property(nonatomic,strong)UIScrollView *resultBoxView;
@property(nonatomic,strong)NSMutableString *boxStr;

@end

@implementation MainViewController
@synthesize calcuArr,calcuBoxView,resultBoxView,boxStr;

- (void)viewDidLoad {
    [super viewDidLoad];
    //数据初始化
    [self initCalcuArr];
    [self initBoxStr];
    
    //UI相关
    [self setBackgroundColor];
    [self addNumberKeyBtn];
    [self addOperatorKeyBtn];
    [self addline];
    [self addCalcuBoxView];
    [self addResultBoxView];
}

/** 输入按钮储存 */
-(void)initCalcuArr{
    calcuArr = [[NSMutableArray alloc] init];
}


/** 初始化运算容器 */
-(void)initBoxStr{
    boxStr = [[NSMutableString alloc] initWithString:@"0"];
}


/** 设置背景颜色 */
-(void)setBackgroundColor{
    [self.view setBackgroundColor:RGB(0, 0, 0)];
}

/** 添加数字按钮 */
-(void)addNumberKeyBtn{
    
    //数字
    NSArray *numArr = @[@"0",@"0",@".",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"];
    
    //for循环添加
    for (int i = 0; i < [numArr count]; i++) {
        //计算数字按钮的x坐标
        float x = i%3*kBasicWidth;
        
        //计算数字按钮的y坐标
        float y = kDeviceHeight-(i/3+1)*kbasicHeight;
        
        //为了合并两个0的操作
        float keyWidth = 0;
        if(i == 0){
            keyWidth = kBasicWidth*2;
        }else if(i == 1){
            continue;
        }else{
            keyWidth = kBasicWidth;
        }
        
        //按钮实例
        UIButton *numBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [numBtn setFrame:CGRectMake(x, y, keyWidth, kbasicHeight)];
        [numBtn setTitle:numArr[i] forState:UIControlStateNormal];
        [numBtn setBackgroundColor:RGB(150, 150, 150)];
        [numBtn setTag:100+i];
        [numBtn addTarget:self
                   action:@selector(keyBtnPressed:)
         forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:numBtn];
    }
}

/** 添加运算符按钮 */
-(void)addOperatorKeyBtn{
    //运算符横向
    NSArray *opxArr = @[@"c",@"÷",@"×",@"←"];
    
    //运算符纵向×
    NSArray *opyArr = @[@"=",@"=",@"+",@"-"];
    
    
    for (int i = 0; i < [opxArr count]; i++) {
        //计算数字按钮的x坐标
        float x = i*kBasicWidth;
        //计算数字按钮的y坐标
        float y = kDeviceHeight-5*kbasicHeight;
        
        //按钮实例
        UIButton *numBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [numBtn setFrame:CGRectMake(x, y, kBasicWidth, kbasicHeight)];
        [numBtn setTitle:opxArr[i] forState:UIControlStateNormal];
        [numBtn setBackgroundColor:RGB(180, 180, 180)];
        [numBtn setTag:200+i];
        [numBtn addTarget:self
                   action:@selector(keyBtnPressed:)
         forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:numBtn];
    }
    
    for (int j = 0; j < [opyArr count]; j++) {
        //计算数字按钮的x坐标
        float x = 3*kBasicWidth;
        //计算数字按钮的y坐标
        float y = kDeviceHeight-(j+1)*kbasicHeight;
        
        //为了合并两个=的操作
        float keyHeight = 0;
        if(j == 0){
            continue;
        }else if(j == 1){
            keyHeight = kbasicHeight*2;
        }else{
            keyHeight = kbasicHeight;
        }
        
        //按钮实例
        UIButton *numBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [numBtn setFrame:CGRectMake(x, y, kBasicWidth, keyHeight)];
        [numBtn setTitle:opyArr[j] forState:UIControlStateNormal];
        [numBtn setBackgroundColor:RGB(180, 180, 180)];
        [numBtn setTag:300+j];
        [numBtn addTarget:self
                   action:@selector(keyBtnPressed:)
         forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:numBtn];
    }
}

/** 添加线条 */
-(void)addline{
    
    //横向线条
    for (int i = 0; i < 4; i++) {
        
        //计算数字按钮的y坐标
        float y = kDeviceHeight-(i+1)*kbasicHeight-0.25;
        
        //判断i=0的情况下线条长度
        float width = kDeviceWidth;
        if(i == 0){
            width = kDeviceWidth - kBasicWidth;
        }
        
        //线条
        UIView *line = [[UIView alloc] init];
        [line setFrame:CGRectMake(0, y, width, 0.5)];
        [line setBackgroundColor:RGB(0, 0, 0)];
        [self.view addSubview:line];
    }
    
    //纵向线条
    for (int i = 0; i < 3; i++) {
        
        //计算数字按钮的y坐标
        float x = (i+1)*kBasicWidth-0.25;
        float y = kDeviceHeight - 5*kbasicHeight;
        
        //判断i=0的情况下线条高度
        float height = 5*kbasicHeight;
        if(i == 0){
            height = 4*kbasicHeight;
        }
        
        //线条
        UIView *line = [[UIView alloc] init];
        [line setFrame:CGRectMake(x, y, 0.5, height)];
        [line setBackgroundColor:RGB(0, 0, 0)];
        [self.view addSubview:line];
    }
}

/** 添加计算界面 */
-(void)addCalcuBoxView{
    
    //坐标宽高
    float cWidth = kDeviceWidth;
    float cHeight = kCalcuLabHeight;
    float x = 0;
    float y = kDeviceHeight - 5*kbasicHeight - cHeight;
    
    //容器scrollview
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    [scrollView setFrame:CGRectMake(x, y, cWidth, cHeight)];
    [scrollView setBackgroundColor:RGBA(0, 0, 0, 0)];
    calcuBoxView = scrollView;
    [self.view addSubview:scrollView];
    
    //初始化一个0
    UIView *view = [self createCalcuBtn:@"0"];
    [view setFrame:CGRectMake(cWidth-kCalcuLabWidth, 0, kCalcuLabWidth, kCalcuLabHeight)];
    [view setTag:1000];
    [scrollView addSubview:view];
    [calcuArr addObject:view];
    
}


-(UIView *)createCalcuBtn:(NSString *)str{
    UIView *view = [[UIView alloc] init];
    [view setBackgroundColor:RGBA(0, 0, 0, 0)];
    
    UILabel *label = [[UILabel alloc] init];
    [label setFrame:CGRectMake(0, 0, kCalcuLabWidth, kCalcuLabHeight)];
    [label setTextAlignment:NSTextAlignmentRight];
    [label setFont:[UIFont systemFontOfSize:kCalcuLabFontSize]];
    [label setTextColor:RGB(255, 255, 255)];
    [label setText:str];
    [view addSubview:label];
    
    return view;
    
}

/** 添加结果界面 */
-(void)addResultBoxView{
    
    //坐标宽高
    float cWidth = kDeviceWidth;
    float cHeight = kDeviceHeight - 5*kbasicHeight - kCalcuLabHeight - 20;
    float x = 0;
    float y = 20;
    
    //容器scrollview
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    [scrollView setFrame:CGRectMake(x, y, cWidth, cHeight)];
    [scrollView setBackgroundColor:RGBA(0, 0, 0, 0)];
    resultBoxView = scrollView;
    [self.view addSubview:scrollView];
    
}


/** 键盘点击事件 */
-(void)keyBtnPressed:(id)sender{
    UIButton *btn = (UIButton *)sender;
    
    NSInteger index = btn.tag;
    
    if(index == 100){
        //0
        [self addNumBtnToInputBox:@"0"];
        
    }else if(index == 102){
        //.
        [self addOperaBtnToInputBox:@"."];
    }else if(index == 103){
        //1
        [self addNumBtnToInputBox:@"1"];
    }else if(index == 104){
        //2
        [self addNumBtnToInputBox:@"2"];
    }else if(index == 105){
        //3
        [self addNumBtnToInputBox:@"3"];
    }else if(index == 106){
        //4
        [self addNumBtnToInputBox:@"4"];
    }else if(index == 107){
        //5
        [self addNumBtnToInputBox:@"5"];
    }else if(index == 108){
        //6
        [self addNumBtnToInputBox:@"6"];
    }else if(index == 109){
        //7
        [self addNumBtnToInputBox:@"7"];
    }else if(index == 110){
        //8
        [self addNumBtnToInputBox:@"8"];
    }else if(index == 111){
        //9
        [self addNumBtnToInputBox:@"9"];
    }else if(index == 200){
        //c
        for (UIView *vv in calcuBoxView.subviews) {
            [vv removeFromSuperview];
        }
        [self initCalcuArr];
        [self initBoxStr];
        UIView *view = [self createCalcuBtn:@"0"];
        [view setFrame:CGRectMake(kDeviceWidth-kCalcuLabWidth, 0, kCalcuLabWidth, kCalcuLabHeight)];
        [view setTag:1000];
        [calcuBoxView addSubview:view];
        [calcuArr addObject:view];
        [calcuBoxView setContentSize:CGSizeMake(0 ,kCalcuLabHeight)];
        
    }else if(index == 201){
        //÷
        [self addOperaBtnToInputBox:@"÷"];
    }else if(index == 202){
        //×
        [self addOperaBtnToInputBox:@"×"];
    }else if(index == 203){
        //←
        UIView *view = [calcuArr lastObject];
        [view removeFromSuperview];
        [calcuArr removeLastObject];
        boxStr = [NSMutableString stringWithFormat:@"%@",[boxStr substringToIndex:boxStr.length-1]];
        if([calcuArr count]*kCalcuLabWidth>=kDeviceWidth){
            [calcuBoxView setContentSize:CGSizeMake([calcuArr count]*kCalcuLabWidth, kCalcuLabHeight)];
            [calcuBoxView setContentOffset:CGPointMake([calcuArr count]*kCalcuLabWidth-kDeviceWidth, 0)];
        }else{
            for (int i = 0; i < [calcuArr count]; i++) {
                NSInteger index = [calcuArr count] - i;
                UIView *view = calcuArr[i];
                //[view setTag:i];
                float x = kDeviceWidth - index*kCalcuLabWidth;
                float y = 0;
                [view setFrame:CGRectMake(x, y, kCalcuLabWidth, kCalcuLabHeight)];
            }
        }
        
        if([calcuArr count] == 0){
            [self initCalcuArr];
            [self initBoxStr];
            UIView *view = [self createCalcuBtn:@"0"];
            [view setFrame:CGRectMake(kDeviceWidth-kCalcuLabWidth, 0, kCalcuLabWidth, kCalcuLabHeight)];
            [view setTag:1000];
            [calcuBoxView addSubview:view];
            [calcuArr addObject:view];
            [calcuBoxView setContentSize:CGSizeMake(0 ,kCalcuLabHeight)];
        }
        
    }else if(index == 300){
        //=
        //NSLog(@"%@",boxStr);
    }else if(index == 301){
        
        NSArray *numArr = [[NSArray alloc] init];
        NSArray *opeArr = [[NSArray alloc] init];
        
        //获取所有数字
        
        numArr = [self getNumberFromStr:boxStr];
        
        //获取所有符号
        opeArr = [self getOpeaFromStr:boxStr];
        
        NSMutableString *add = [[NSMutableString alloc] init];
        float ji = 1;
        for (int i = 0; i < [opeArr count]; i++) {
            if([opeArr[i] isEqualToString:@"×"]){
                if(ji != 1){
                    ji = ji * [numArr[i+1] floatValue];
                }else{
                    ji = [numArr[i] floatValue] * [numArr[i+1] floatValue];
                }
            }else if([opeArr[i] isEqualToString:@"÷"]){
                if(ji != 1){
                    ji = ji / [numArr[i+1] floatValue];
                }else{
                    ji = [numArr[i] floatValue] / [numArr[i+1] floatValue];
                }
            }else{
                if(ji != 1){
                    [add appendString:[NSString stringWithFormat:@"%f%@",ji,opeArr[i]]];
                    ji = 1;
                }else{
                    [add appendString:[NSString stringWithFormat:@"%@%@",numArr[i],opeArr[i]]];
                }
            }
        }
        
        if(ji != 1){
            [add appendString:[NSString stringWithFormat:@"%f",ji]];
        }
        
        if([opeArr[opeArr.count-1] isEqualToString:@"+"] || [opeArr[opeArr.count-1] isEqualToString:@"-"]){
            [add appendString:[NSString stringWithFormat:@"%@",numArr[numArr.count-1]]];
        }
        
        
        //获取所有数字
        numArr = [self getNumberFromStr:add];
        
        //获取所有符号
        opeArr = [self getOpeaFromStr:add];
        
        float sum = [numArr[0] floatValue];
        
        for (int i = 0; i<opeArr.count; i++) {
            if([opeArr[i] isEqualToString:@"+"]){
                sum = sum + [numArr[i+1] floatValue];
            }else{
                sum = sum - [numArr[i+1] floatValue];
            }
        }
        
//        if([opeArr[0] isEqualToString:@"+"]){
//            sum = sum + [numArr[0] floatValue];
//        }else{
//            sum = sum - [numArr[0] floatValue];
//        }
        
        UILabel *label = [[UILabel alloc] init];
        [label setFrame:CGRectMake(0, 0, kDeviceWidth, 50)];
        [label setNumberOfLines:0];
        [label setFont:[UIFont systemFontOfSize:18.0]];
        [label setTextColor:RGB(255, 255, 255)];
        [label setText:[NSString stringWithFormat:@"%@=%.5f",[boxStr substringFromIndex:1],sum]];
        [resultBoxView addSubview:label];
        NSLog(@"%@",add);
        NSLog(@"%.5f",sum);
        
        
    }else if(index == 302){
        //+
        [self addOperaBtnToInputBox:@"+"];
    }else if(index == 303){
        //-
        [self addOperaBtnToInputBox:@"-"];
    }
    
    
    for (int i = 0; i < [calcuArr count]; i++) {
        
        //计算滑动区域
        if([calcuArr count]*kCalcuLabWidth>=kDeviceWidth){
            NSInteger index = i;
            UIView *view = calcuArr[index];
            //[view setTag:index];
            float x = index*kCalcuLabWidth;
            float y = 0;
            [view setFrame:CGRectMake(x, y, kCalcuLabWidth, kCalcuLabHeight)];
            
            [calcuBoxView setContentSize:CGSizeMake((index+1)*kCalcuLabWidth, kCalcuLabHeight)];
            [calcuBoxView setContentOffset:CGPointMake((index+1)*kCalcuLabWidth-kDeviceWidth, 0)];
        }else{
            NSInteger index = [calcuArr count] - i;
            UIView *view = calcuArr[i];
            //[view setTag:i];
            float x = kDeviceWidth - index*kCalcuLabWidth;
            float y = 0;
            [view setFrame:CGRectMake(x, y, kCalcuLabWidth, kCalcuLabHeight)];
        }
    }

}

/** 从字符串中获取所有数字 */
-(NSArray *)getNumberFromStr:(NSString *)str{
    NSMutableArray *numArr = [[NSMutableArray alloc] init];
    
    //获取所有数字
    NSString *regex = @"\\d*\\.{0,1}\\d*\\d";
    NSError *error;
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:regex
                                                                             options:NSRegularExpressionCaseInsensitive
                                                                               error:&error];
    NSArray *matches = [regular matchesInString:str
                                        options:0
                                          range:NSMakeRange(0, str.length)];
    for (NSTextCheckingResult *match in matches) {
        NSRange range = [match range];
        NSString *mStr = [str substringWithRange:range];
        [numArr addObject:mStr];
    }
    
    return numArr;
}

/** 从字符串中获取所有符号 */
-(NSArray *)getOpeaFromStr:(NSString *)str{
    NSMutableArray *numArr = [[NSMutableArray alloc] init];
    
    //获取所有数字
    NSString *regex = @"\\+|\\-|\\×|\\÷";
    NSError *error;
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:regex
                                                                             options:NSRegularExpressionCaseInsensitive
                                                                               error:&error];
    NSArray *matches = [regular matchesInString:str
                                        options:0
                                          range:NSMakeRange(0, str.length)];
    for (NSTextCheckingResult *match in matches) {
        NSRange range = [match range];
        NSString *mStr = [str substringWithRange:range];
        [numArr addObject:mStr];
    }
    
    return numArr;
}


/** 添加数字btn到界面上的方法 */
-(void)addNumBtnToInputBox:(NSString *)str{
    UIView * v= calcuArr[0];
    
    if([calcuArr count] == 1 && [str isEqualToString:@"0"]){
        return;
    }
    
    if([calcuArr count] == 1 && v.tag == 1000){
        
        //删除容器里所有的view
        for (UIView *vv in calcuBoxView.subviews) {
            [vv removeFromSuperview];
        }
        calcuArr = [[NSMutableArray alloc] init];
    }
    
    UIView *view = [self createCalcuBtn:str];
    [calcuArr addObject:view];
    [calcuBoxView addSubview:view];
    
    [boxStr appendString:str];
}


/** 添加运算符号btn到界面上的方法 */
-(void)addOperaBtnToInputBox:(NSString *)str{
    
    UIView *v = [calcuArr lastObject];
    if(v.tag == 999){
        return;
    }
    
    UIView *view = [self createCalcuBtn:str];
    [view setTag:999];
    [calcuArr addObject:view];
    [calcuBoxView addSubview:view];
    
    [boxStr appendString:str];
}

@end
